package com.mina.server;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;

public class InfoIOFilterS extends IoFilterAdapter {
	private static Logger logger = Logger.getLogger(InfoIOFilterS.class);

	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session,
			Object message) throws Exception {
		IoBuffer ioBuffer = (IoBuffer) message;
		message = ioBuffer.getHexDump().replaceAll(" ", "");
		nextFilter.messageReceived(session, message);

//		if (!message.toString().startsWith("6801")) {
//			session.close(true);
//		} else {
//			nextFilter.messageReceived(session, message);
//		}
	}

	@Override
	public void filterWrite(NextFilter nextFilter, IoSession session,
			WriteRequest writeRequest) throws Exception {
		logger.debug("filterWrite");
		super.filterWrite(nextFilter, session, writeRequest);
	}

	public static String ioBufferToString(Object message) {
		if (!(message instanceof IoBuffer)) {
			return "";
		}
		IoBuffer ioBuffer = (IoBuffer) message;
		byte[] b = new byte[ioBuffer.limit()];
		ioBuffer.get(b);
		StringBuffer stringBuffer = new StringBuffer();

		for (int i = 0; i < b.length; i++) {

			stringBuffer.append(b[i]);
		}
		return stringBuffer.toString();
	}
}
